import * as fs from "fs";
import * as path from "path";
import * as jwt from "jsonwebtoken";

const rootDir = process.cwd()
const currentDir = __dirname
const privateKey = fs.readFileSync(path.join(rootDir, 'environment', 'jwt-private.key'), { encoding: "utf-8" });
const expiresInSeconds: number = 30 * 60;

export function generateAccessToken(userId: string, account: string): { accessToken: string, accessTokenExpiration: Date } {
    const accessTokenExpirationMsSinceEpoch: number = Date.now() + (expiresInSeconds * 1000);
    return {
        'accessToken': jwt.sign({ userId: userId, account: account }, privateKey, {
            expiresIn: expiresInSeconds
        }),
        'accessTokenExpiration': new Date(accessTokenExpirationMsSinceEpoch)
    }
}
export function verifyJwtAccessToken(jwtAccessToken: string): { valid: boolean, userId?: string, account?: string, error?: any } {
    try {
        const { account, userId } = jwt.verify(jwtAccessToken, privateKey);
        return {
            valid: true,
            userId: userId,
            account: account,
        };
    } catch (error: any) {
        return {
            valid: false,
            error: error
        };
    }
}
export function generateRefreshToken() {
    //https://stackoverflow.com/a/8084248/4508758
    return (Math.random() + 1).toString(36).substring(2);
}
